﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Development.Tools
{
    public class ActionQueue : Singleton<ActionQueue>
    {
        private Queue<Action> m_actionQueue = new Queue<Action>();
        private int m_count = 0;
        public void OnRun()
        {
            Action a = DeQueue();
            if(a != null)
            {
                a();
            }
        }

        /// <summary>
        /// count of queue
        /// </summary>
        public int Count { get { return m_count; } }

        /// <summary>
        /// enter msg in queue
        /// </summary>
        /// <param name="msg"></param>
        public void EnQueue(Action action)
        {
            lock (m_actionQueue)
            {
                m_actionQueue.Enqueue(action);
                Interlocked.Increment(ref m_count);
            }
        }


        /// <summary>
        /// get one msg from queue ,if the count is zero retun null
        /// </summary>
        /// <returns></returns>
        public Action DeQueue()
        {
            lock (m_actionQueue)
            {
                if (m_actionQueue.Count > 0)
                {
                    Action msg = m_actionQueue.Dequeue();
                    Interlocked.Decrement(ref m_count);
                    return msg;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}
